{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Motion correction in ANTsPy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We rely on ants.registration to do motion correction which provides the user with full access to parameters and outputs.  The key steps, then, are to:\n",
    "* split the N dimensional (e.g. N=4) image to a list of N-1 dimensional images\n",
    "* run registration to a selected fixed image for each image in the list\n",
    "* merge the results back to a N dimensional image.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ants\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We illustrate the steps below by building a 3D \"functional\" image and then \"motion correcting\" just as we would do with functional MRI or any other dynamic modality."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = ants.image_read(ants.get_ants_data('r16'))\n",
    "image2 = ants.image_read(ants.get_ants_data('r64'))\n",
    "ants.set_spacing( image, (2,2) )\n",
    "ants.set_spacing( image2, (2,2) )\n",
    "imageTar = ants.make_image( ( *image2.shape, 2 ) )\n",
    "ants.set_spacing( imageTar, (2,2,2) )\n",
    "fmri = ants.list_to_ndimage( imageTar, [image,image2] )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we motion correct this image just using the first slice as target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "ants.set_direction( fmri, np.eye( 3 ) * 2 )\n",
    "images_unmerged = ants.ndimage_to_list( fmri )\n",
    "motion_corrected = list()\n",
    "for i in range( len( images_unmerged ) ):\n",
    "    areg = ants.registration( images_unmerged[0], images_unmerged[i], \"SyN\" )\n",
    "    motion_corrected.append( areg[ 'warpedmovout' ] )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Merge the resuling list back to a 3D image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "motCorr = ants.list_to_ndimage( fmri, motion_corrected )\n",
    "# ants.image_write( motCorr, '/tmp/temp.nii.gz' )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Done!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
